package com.heima.admin.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.heima.admin.feign.ArticleFeign;
import com.heima.admin.feign.WemediaFeign;
import com.heima.admin.mapper.AdChannelMapper;
import com.heima.admin.service.AdSensitiveService;
import com.heima.admin.service.WemediaNewsAutoScanService;
import com.heima.common.aliyun.GreeTextScan;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.fastdfs.FastDFSClient;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.admin.pojos.AdChannel;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.wemedia.vo.WmNewsVo;
import com.heima.utils.common.SensitiveWordUtil;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.elasticsearch.rest.RestClientAutoConfiguration;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.*;

@Service
@Log4j2
public class WemediaNewsAutoScanServiceImpl implements WemediaNewsAutoScanService {
    @Autowired
    private WemediaFeign wemediaFeign;
    @Value("${fdfs.url}")
    private String fileServerUrl;
    @Autowired
    private GreeTextScan greeTextScan;
    @Autowired
    private GreenImageScan greenImageScan;
    @Autowired
    private FastDFSClient fastDFSClient;
    @Autowired
    private AdSensitiveService adSensitiveService;
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public void autoScanByMediaNewsId(Integer id) {
        //参数校验
        if (id == null) {
            log.error("当前审核的id为空");
            return;
        }
        //1.根据id查询当前自媒体文章信息
        WmNews wmNews = wemediaFeign.findById(String.valueOf(id));
        if (wmNews == null) {
            log.error("审核的自媒体文章不存在，自媒体的id:{}", id);
            return;
        }
        //2.文章状态为4（人工审核通过）直接保存数据和创建索引
        if (wmNews.getStatus() == 4) {
            //保存数据
            saveAppArticle(wmNews);
            return;
        }

        //3.文章状态为8  发布时间小于等于当前时间 直接保存数据
        if (wmNews.getStatus() == 8 && wmNews.getPublishTime().getTime() <= System.currentTimeMillis()) {
            //保存数据
            saveAppArticle(wmNews);
            return;
        }

        //4.当前文章状态为1,待审核
        if (wmNews.getStatus() == 1) {
            //抽取文章内容中的纯文本和图片
            Map<String, Object> contentAndImagesResult = handleTextAndImages(wmNews);
            //4.1 文本审核
            boolean textScanBoolean = handleTextScan(contentAndImagesResult.get("content").toString(), wmNews);
            if (!textScanBoolean) return;
            //4.2 图片审核
            boolean imagesScanBoolean = handleImagesScan((List<String>) contentAndImagesResult.get("images"), wmNews);
            if (!imagesScanBoolean) return;
            //4.3自管理的敏感词管理
            boolean sensitiveScanBoolean = handleSensitive(contentAndImagesResult.get("content").toString(), wmNews);
            if (!sensitiveScanBoolean) return;
            //4.4 发布时间大于当前时间
            if (wmNews.getPublishTime().getTime() > System.currentTimeMillis()) {
                //修改文章时间为8
                updateWmNews(wmNews, (short) 8, "审核通过,待发布");
                return;
            }
            //5.审核通过，修改自媒体文章状态为9  保存app端相关文章信息
            saveAppArticle(wmNews);
        }


    }

    /**
     * 保存app文章相关的数据
     *
     * @param wmNews
     */
    private void saveAppArticle(WmNews wmNews) {
        //保存app文章
        ApArticle apArticle = saveArticle(wmNews);
        //保存文章配置
        saveArticleConfig(apArticle);
        //保存app文章内容
        saveArticleContent(apArticle, wmNews);

        //修改自媒体文章的状态为9
        wmNews.setArticleId(apArticle.getId());
        updateWmNews(wmNews, (short) 9, "审核通过");
        //保存发布文章到ElasticSearch中
        Map<String,Object> map=new HashMap<>();
        map.put("id",apArticle.getId().toString());
        map.put("publishTime",apArticle.getPublishTime());
        map.put("layout",apArticle.getLayout());
        map.put("images",apArticle.getImages());
        map.put("authorId",apArticle.getAuthorId());
        map.put("title",apArticle.getTitle());
        map.put("content",wmNews.getContent());
        IndexRequest indexRequest=new IndexRequest("app_info_article")
                .id(apArticle.getId().toString()).source(map);
        try {
            this.restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    @Autowired
    private ArticleFeign articleFeign;
    @Autowired
    private AdChannelMapper adChannelMapper;

    /**
     * 保存app文章内容
     *
     * @param apArticle
     * @param wmNews
     */
    private void saveArticleContent(ApArticle apArticle, WmNews wmNews) {
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticle.getId());
        apArticleContent.setContent(wmNews.getContent());
        articleFeign.saveArticleContent(apArticleContent);
    }

    //保存文章配置
    private void saveArticleConfig(ApArticle apArticle) {
        ApArticleConfig apArticleConfig = new ApArticleConfig();
        apArticleConfig.setArticleId(apArticle.getId());
        apArticleConfig.setIsForward(true);
        apArticleConfig.setIsDelete(false);
        apArticleConfig.setIsDown(true);
        apArticleConfig.setIsComment(true);
        articleFeign.saveArticleConfig(apArticleConfig);
    }

    //保存APP文章
    private ApArticle saveArticle(WmNews wmNews) {
        ApArticle apArticle = new ApArticle();
        apArticle.setTitle(wmNews.getTitle());
        apArticle.setLayout(wmNews.getType());
        apArticle.setImages(wmNews.getImages());
        apArticle.setCreatedTime(new Date());

        Integer userId = wmNews.getUserId();
        WmUser wmUser = wemediaFeign.findWmUserById(String.valueOf(userId));
        if (wmUser != null) {
            String name = wmUser.getName();
            ApAuthor apAuthor = articleFeign.selectAuthorByName(name);
            if (apArticle != null) {
                apArticle.setAuthorName(apAuthor.getName());
                apArticle.setAuthorId(Long.valueOf(apAuthor.getUserId()));
            }
        }
        //获取频道相关信息
        Integer channelId = wmNews.getChannelId();
        AdChannel adChannel = adChannelMapper.selectById(channelId);
        if (adChannel != null) {
            apArticle.setChannelId(adChannel.getId());
            apArticle.setChannelName(adChannel.getName());
        }
        return articleFeign.saveArticle(apArticle);

    }

    //自管理的敏感词审核
    private boolean handleSensitive(String content, WmNews wmNews) {
        boolean flag = true;
        List<String> allSensitive = adSensitiveService.findAllSensitive();
        //初始化敏感词
        SensitiveWordUtil.initMap(allSensitive);
        //文章内容自管理敏感词过滤
        Map<String, Integer> resultMap = SensitiveWordUtil.matchWords(content);
        if (resultMap.size() > 0) {
            log.error("敏感词过滤没有通过,包含了敏感词{}", resultMap);
            updateWmNews(wmNews, (short) 2, "文章包含了敏感词");
            flag = false;
        }
        return flag;
    }

    //图片审核
    private boolean handleImagesScan(List<String> images, WmNews wmNews) {
        if (images == null) {
            return true;
        }
        List<byte[]> imageList = new ArrayList<>();
        boolean flag = true;
        for (String image : images) {
            String imageName = image.replace(fileServerUrl, "");
            int index = imageName.indexOf("/");
            String groupName = imageName.substring(0, index);
            String imagePath = imageName.substring(index + 1);
            try {
                byte[] bytes = fastDFSClient.download(groupName, imagePath);
                imageList.add(bytes);
                //阿里云图片审核
                Map map = greenImageScan.imageScan(imageList);
                //审核不通过
                if (!map.get("suggestion").equals("pass")) {
                    //审核失败
                    if (map.get("suggestion").equals("block")) {
                        updateWmNews(wmNews, (short) 2, "图片有违法信息!!");
                        flag = false;
                    }
                    //人工审核
                    if (map.get("suggestion").equals("review")) {
                        updateWmNews(wmNews, (short) 3, "文章图片有不确定因素!!");
                        flag = false;
                    }
                }
            } catch (Exception e) {
                flag = false;
                e.printStackTrace();
            }
        }
        return flag;
    }

    //文本审核
    private boolean handleTextScan(String content, WmNews wmNews) {
        //默认审核通过
        boolean flag = true;
        try {
            Map map = greeTextScan.greeTextScan(content);
            //审核未通过
            if (!map.get("suggestion").equals("pass")) {
                //审核失败
                if (map.get("suggestion").equals("block")) {
                    //修改自媒体文章的状态,并放回失败原因
                    updateWmNews(wmNews, (short) 2, "文章内容中有敏感词汇");
                    flag = false;
                }
                //人工审核
                if (map.get("suggestion").equals("review")) {
                    //修改自媒体文章的状态，并告知审核失败原因
                    updateWmNews(wmNews, (short) 3, "文中内容有不确定词汇");
                    flag = false;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
        return flag;
    }

    /**
     * 修改自媒体文章
     *
     * @param wmNews
     * @param status
     * @param msg
     */
    private void updateWmNews(WmNews wmNews, short status, String msg) {
        wmNews.setStatus(status);
        wmNews.setReason(msg);
        wemediaFeign.updateWmNews(wmNews);
    }

    //抽取文章或图片信息
    private Map<String, Object> handleTextAndImages(WmNews wmNews) {
        //文章的内容
        String content = wmNews.getContent();
        //获取文章图片的集合
        List<Map> contentList = JSONArray.parseArray(content, Map.class);
        //文章
        StringBuilder contentStr = new StringBuilder();
        //图片集合
        List<String> imagesList = new ArrayList<>();
        for (Map map : contentList) {
            if (map.get("type").equals("text")) {
                contentStr.append(map.get("value"));
            }
            if (map.get("type").equals("image")) {
                imagesList.add((String) map.get("value"));
            }
        }
        if (wmNews.getImages() != null && wmNews.getType() != 0) {
            String[] split = wmNews.getImages().split(",");
            imagesList.addAll(Arrays.asList(split));
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("content", contentStr);
        resultMap.put("images", imagesList);
        return resultMap;
    }

    /**
     * 根据文章标题分页查询自媒体文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findNews(NewsAuthDto dto) {
        //校验参数
        dto.checkParam();
        //分页查寻
        PageResponseResult list = wemediaFeign.findList(dto);
        list.setHost(fileServerUrl);
        return list;
    }

    /**
     * 根据文章id文章信息
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult findOne(Integer id) {
        //参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询数据
        WmNewsVo wmNewsVo = wemediaFeign.findWmNewsVo(id);
        //封装参数
        ResponseResult responseResult = ResponseResult.okResult(wmNewsVo);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    /**
     * 审核通过或驳回
     *
     * @param type 0 为驳回  1位通过
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateStatus(Integer type, NewsAuthDto dto) {
        //校验参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询文章
        WmNews wmNews = wemediaFeign.findById(String.valueOf(dto.getId()));
        if (wmNews==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //审核没有通过
        if(type.equals(0)){
            updateWmNews(wmNews,(short)2,dto.getMsg());
        }else if(type.equals(1)){
            //人工审核通过
            updateWmNews(wmNews,(short)4,"人工审核通过");
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
